<?php
namespace lib\wechat;

/**
 * 接口集成
 * @Auth: JH <hu@lunaz.cn>
 * Class Tools
 * @package lib\wechat
 */
class Tools extends Base
{

    /**
     * @param array $options
     * @param string $access_token
     */
    function __construct( array $options = array(), $access_token = '' )
    {
        if ($access_token) {
            parent::$accessToken = $access_token;
        }
        if ($options) {
            parent::$config = $options;
        }
        parent::__construct();
    }

    /**
     * 长网址转短网址
     * @param string $long_url
     * @return false|url
     * @throws Exception
     */
    function url( $long_url = '' )
    {
        $result = $this->http(
            $this->makeUrl( '/shorturl', $this->getAccessToken() ),
            array(
                'action' => 'long2short',
                'long_url' => $long_url
            )
        );
        if (isset( $result['short_url'] )) {
            return $result['short_url'];
        }
        return false;
    }

    /**
     * 通过ticket换取二维码
     * @param string $ticket
     * @return string
     */
    function qrSrc( $ticket )
    {
        return 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . urlencode( $ticket );
    }

    /**
     * 获取微信服务器IP地址列表
     * @return false|array
     * <pre>
     * Array(
     *      [0] => 101.226.62.77
     *      [1] => 101.226.62.78
     *      [2] => 101.226.62.79
     *      ...
     * )
     * </pre>
     * @throws Exception
     */
    function ipList()
    {
        $result = $this->http(
            $this->makeUrl( '/getcallbackip', $this->getAccessToken() )
        );
        if (isset( $result['ip_list'] )) {
            return $result['ip_list'];
        }
        return false;
    }

    /**
     * 获取公众号的自动回复规则
     * @return array|bool|mixed
     * @throws Exception
     */
    function autoReplyInfo()
    {
        return $this->http(
            $this->makeUrl( '/get_current_autoreply_info', $this->getAccessToken() )
        );
    }

    /**
     * 获取用户增减数据
     * @param int $day
     * @return array|false
     * <pre>
     * Array(
     *      [0] => Array(
     *          [ref_date] => 2016-06-18
     *          [user_source] => 0
     *          [new_user] => 0
     *          [cancel_user] => 0
     *      )
     *      [0] => Array(
     *          [ref_date] => 2016-06-18
     *          [user_source] => 1 //0代表其他合计 1代表公众号搜索 17代表名片分享 30代表扫描二维码 43代表图文页右上角菜单 51代表支付后关注（在支付完成页） 57代表图文页内公众号名称 75代表公众号文章广告 78代表朋友圈广告
     *          [new_user] => 1 //新增的用户数量
     *          [cancel_user] => 0 //取消关注的用户数量，new_user减去cancel_user即为净增用户数量
     *      )
     *      ........
     * )
     * </pre>
     * @throws Exception
     */
    function getUserSummary( $day = 1 )
    {
        return $this->getList( 'getusersummary', $day );
    }


    /**
     * @param int $day
     * @return bool|array
     * <pre>
     * Array(
     *      [0] => Array(
     *          [ref_date] => 2016-06-18
     *          [user_source] => 0
     *          [cumulate_user] => 3 //总用户量
     *      )
     *      ....
     * )
     * </pre>
     * @throws Exception
     */
    function getUserCumulate( $day = 1 )
    {
        return $this->getList( 'getusercumulate', $day );
    }

    /**
     * 获取图文群发每日数据
     * @param int $day
     * @return false|array
     * 返回数组详情
     * @link https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141084
     */
    function getArticleSummary( $day = 1 )
    {
        return $this->getList( 'getarticlesummary', $day, 1 );
    }

    /**
     * 获取图文群发总数据
     * @param int $day
     * @return false|array
     * 返回数组详情
     * @link https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141084
     */
    function getArticleTotal( $day = 1 )
    {
        return $this->getList( 'getarticletotal', $day, 1 );
    }

    /**
     * 获取图文阅读统计数据
     * @param int $day
     * @return false|array
     * 返回数组详情
     * @link https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141084
     */
    function getUserRead( $day = 1 )
    {
        return $this->getList( 'getuserread', $day, 3 );
    }

    /**
     * 获取图文阅读统计时段数据
     * @param int $day
     * @return false|array
     * 返回数组详情
     * @link https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141084
     */
    function getUserReadHour( $day = 1 )
    {
        return $this->getList( 'getuserreadhour', $day, 3 );
    }

    /**
     * 获取图文分享转发数据
     * @param int $day
     * @return false|array
     * 返回数组详情
     * @link https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141084
     */
    function getUserShare( $day = 1 )
    {
        return $this->getList( 'getusershare', $day, 7 );
    }

    /**
     * 获取图文分享转发时段数据
     * @param int $day
     * @return false|array
     * 返回数组详情
     * @link https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141084
     */
    function getUserShareHour( $day = 1 )
    {
        return $this->getList( 'getusersharehour', $day, 1 );
    }

    /**
     * 获取消息发送概况数据
     * @param int $day
     * @return false|array
     * 返回数据参考
     * @link https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141085
     */
    function getUpStreamMsg( $day = 1 )
    {
        return $this->getList( 'getupstreammsg', $day );
    }

    /**
     * 获取消息分送分时数据
     * @param int $day
     * @return false|array
     * 返回数据参考
     * @link https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141085
     */
    function getUpStreamMsgHour( $day = 1 )
    {
        return $this->getList( 'getupstreammsghour', $day, 1 );
    }

    /**
     * 获取消息发送周数据
     * @param int $day
     * @return false|array
     * 返回数据参考
     * @link https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141085
     */
    function getUpStreamMsgWeek( $day = 1 )
    {
        $this->getList( 'getupstreammsgweek', $day, 30 );
    }

    /**
     * 获取消息发送月数据
     * @param int $day
     * @return false|array
     * 返回数据参考
     * @link https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141085
     */
    function getUpStreamMsgMonth( $day = 1 )
    {
        $this->getList( 'getupstreammsgmonth', $day, 30 );
    }

    /**
     * 获取消息发送分布数据
     * @param int $day
     * @return false|array
     * 返回数据参考
     * @link https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141085
     */
    function getUpStreamMsgDist( $day = 1 )
    {
        return $this->getList( 'getupstreammsgdist', $day, 15 );
    }

    /**
     * 获取消息发送分布周数据
     * @param int $day
     * @return false|array
     * 返回数据参考
     * @link https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141085
     */
    function getUpStreamMsgDistWeek( $day = 1 )
    {
        return $this->getList( 'getupstreammsgdistweek', $day, 30 );
    }

    /**
     * 获取消息发送分布月数据
     * @param int $day
     * @return false|array
     * 返回数据参考
     * @link https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141085
     */
    function getUpStreamMsgDistMonth( $day = 1 )
    {
        return $this->getList( 'getupstreammsgdistmonth', $day, 30 );
    }

    /**
     * 获取接口分析数据
     * @param int $day
     * @return false|array
     * <pre>
     * Array(
     *      Array(
     *          [ref_date] => 2014-12-07 //数据的日期
     *          [callback_count] => 36974 //通过服务器配置地址获得消息后，被动回复用户消息的次数
     *          [fail_count] => 67 //上述动作的失败次数
     *          [total_time_cost] => 14994291 //总耗时，除以callback_count即为平均耗时
     *          [max_time_cost] => 5044 //最大耗时
     *      ),
     *      ......
     * )
     * </pre>
     */
    function getInterFaceSummary( $day = 1 )
    {
        return $this->getList( 'getinterfacesummary', $day, 30 );
    }

    /**
     * 获取接口分析时段数据
     * @param int $day
     * @return false|array
     * <pre>
     * Array(
     *      Array(
     *          [ref_date] => 2014-12-07 //数据的日期
     *          [ref_hour] => 0 //数据的小时
     *          [callback_count] => 36974 //通过服务器配置地址获得消息后，被动回复用户消息的次数
     *          [fail_count] => 67 //上述动作的失败次数
     *          [total_time_cost] => 14994291 //总耗时，除以callback_count即为平均耗时
     *          [max_time_cost] => 5044 //最大耗时
     *      ),
     *      .....
     * )
     * </pre>
     */
    function getInterFaceSummaryHour( $day = 1 )
    {
        return $this->getList( 'getinterfacesummaryhour', $day, 1 );
    }

    private function getList( $path, $day, $max = 7 )
    {
        $date = $this->diffDate( $day, $max );
        $result = $this->http(
            $this->makeUrl( "/datacube/{$path}", $this->getAccessToken(), parent::API_BASE ),
            $date
        );
        if (isset( $result['list'] )) {
            return $result['list'];
        }
        return false;
    }


    private function diffDate( $day, $max )
    {
        $begin = max( 1, min( $max, (int)$day ) );
        $time = time() - 86400; //结束时间只能到昨天
        return array(
            'begin_date' => date( 'Y-m-d', strtotime( "-{$begin} day" ) ),
            'end_date' => date( 'Y-m-d', $time )
        );
    }
}